﻿namespace KinonekoSoftware.Studio.Enums
{
    public sealed class EnumMaster<T> where T : struct, Enum
    {
        internal         int              value;
        private readonly List<EnumChoice> _servants;

        public EnumMaster()
        {
            _servants = new List<EnumChoice>();
        }

        internal void NotifyChanges()
        {
            //
            //
            _servants.ForEach(x => x.RaiseUpdated());
        }

        /// <summary>
        /// 获得当前的值。
        /// </summary>
        public T Value
        {
            get
            {
                if (GetValueConverter is not null)
                {
                    return GetValueConverter(value);
                }
                
                return EnumStatic.IntToEnum<T>(value);
            }
            set
            {
                if (SetValueConverter is not null)
                {
                    this.value = SetValueConverter(value);
                    return;
                }
                
                //
                //
                this.value = Convert.ToInt32(value);
            }
        }

        public Func<T, int> SetValueConverter { get; set; }
        public Func<int, T> GetValueConverter { get; set; }

        public EnumSingleSelect<T> SingleSelect(string propertyName, T defaultValue, Action<string> callback, Action<T> handler = null)
        {
            var servant = new EnumSingleSelect<T>(defaultValue, propertyName, callback, this, handler);

            _servants.Add(servant);

            return servant;
        }

        public EnumMultiSelect<T> MultiSelect(string propertyName, T defaultValue, Action<string> callback, Action<T> handler = null)
        {
            var servant = new EnumMultiSelect<T>(defaultValue, propertyName, callback, this, handler);

            _servants.Add(servant);

            return servant;
        }
    }
}